package mil.af.amc.adpetracker.web.actions.EquipmentItem;

import mil.af.amc.adpetracker.web.actions.AbstractAction;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.service.ServiceException;
import org.apache.struts.action.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Action to assign equipment items to a user
 *
 * @author TSgt Jason Ferguson
 */

public class AssignEquipmentItemToUserAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(AssignEquipmentItemToUserAction.class);

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        DynaActionForm form = (DynaActionForm) actionForm;
        Map itemMap = form.getMap();

        int userId = Integer.parseInt(httpServletRequest.getParameter("userId"));
        itemMap.put("userId", userId);

        try {
            equipmentItemService.assignItem(itemMap);
        } catch (ServiceException e) {
            ActionMessage message = new ActionMessage(e.getKey());
            saveError(httpServletRequest, message);
            log.debug(e);
        }

        if (itemMap.get("serial") != null) {
            return actionMapping.findForward("userProfile");
        }

        // We're done with the itemTypeId now
        httpServletRequest.getSession().setAttribute("equipmentTypeId", null);

        return actionMapping.findForward("itemProfile");

    }
}
